package com.hutu.comment.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hutu.comment.adaptor.CommentDtoAdaptor;
import com.hutu.comment.domain.TbComment;
import com.hutu.comment.domain.TbEditorData;
import com.hutu.comment.domain.TbUserCollectedComment;
import com.hutu.comment.domain.TbUserLikedComment;
import com.hutu.comment.domain.dto.CommentDto;
import com.hutu.comment.domain.dto.request.CommentQueryRequest;
import com.hutu.comment.service.TbCommentService;
import com.hutu.comment.mapper.TbCommentMapper;
import com.hutu.comment.service.TbEditorDataService;
import com.hutu.comment.service.TbUserCollectedCommentService;
import com.hutu.comment.service.TbUserLikedCommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 20272
 * @description 针对表【tb_comment(评论表)】的数据库操作Service实现
 * @createDate 2025-03-17 22:08:45
 */
@Service
@RequiredArgsConstructor
public class TbCommentServiceImpl extends ServiceImpl<TbCommentMapper, TbComment>
        implements TbCommentService {

    private final TbUserLikedCommentService tbUserLikedCommentService;
    private final TbUserCollectedCommentService tbUserCollectedCommentService;
    private final TbEditorDataService tbEditorDataService;

    @Override
    public Page<CommentDto> commentPage(CommentQueryRequest commentQueryRequest) {
        // 一次性获取该问题下的全部评论
        List<TbComment> commentList = lambdaQuery()
                .eq(TbComment::getQuestionId, commentQueryRequest.getQuestionId())
                .list();



    }

    public Map<Integer, Long> getCollectedCount(Set<Integer> commentIds) {
        // 获取所有评论的点赞记录
        List<TbUserCollectedComment> collected = tbUserCollectedCommentService.lambdaQuery()
                .in(TbUserCollectedComment::getCommentId, commentIds).list();
        // 进行划分
        return collected.stream()
                .collect(Collectors.groupingBy(TbUserCollectedComment::getCommentId, Collectors.counting()))
    }

    public Map<Integer, Boolean> getCollected(String username, Set<Integer> commentIds) {
        // 根据用户名称获取点赞的集合,批量
        List<TbUserCollectedComment> collectedComments = tbUserCollectedCommentService.lambdaQuery()
                .eq(TbUserCollectedComment::getUsername, username)
                .list();
        // 进行划分
        Set<Integer> collected = collectedComments.stream()
                .map(TbUserCollectedComment::getCommentId)
                .collect(Collectors.toSet());
        Map<Integer, Boolean> map = new HashMap<>();
        for (Integer comment : collected) {
            if (commentIds.contains(comment)) {
                map.put(comment, Boolean.TRUE);
            }
        }
        return map;
    }

    /**
     * 判断用户是否点赞过
     *
     * @param username
     * @param commentIds
     * @return
     */
    public Map<Integer, Boolean> getLiked(String username, Set<Integer> commentIds) {
        // 根据用户名称获取点赞的集合,批量
        List<TbUserLikedComment> likedComments = tbUserLikedCommentService.lambdaQuery()
                .eq(TbUserLikedComment::getUsername, username)
                .list();
        // 进行划分
        Set<Integer> comments = likedComments.stream()
                .map(TbUserLikedComment::getCommentId)
                .collect(Collectors.toSet());
        Map<Integer, Boolean> map = new HashMap<>();
        for (Integer comment : comments) {
            if (commentIds.contains(comment)) {
                map.put(comment, Boolean.TRUE);
            }
        }
        return map;
    }


    /**
     * 每条评论的点赞数集合,批量获取
     */
    public Map<Integer, Long> getLikedCount(Set<Integer> commentIds) {
        // 获取所有评论的点赞记录
        List<TbUserLikedComment> likedComments = tbUserLikedCommentService.lambdaQuery()
                .in(TbUserLikedComment::getCommentId, commentIds).list();
        // 进行划分
        return likedComments.stream()
                .collect(Collectors.groupingBy(TbUserLikedComment::getCommentId, Collectors.counting()))
    }

    /**
     * 创建树和构造对象
     *
     * @param comments
     * @return
     */
    public List<CommentDto> buildCommentTree(List<TbComment> comments,CommentQueryRequest commentQueryRequest) {
        // 获取回答的内容
        Map<Integer, String> commentContentMap = buildCommentContentMap(comments);
        // 获取评论id集合
        Set<Integer> commentIds = comments.stream().map(TbComment::getId).collect(Collectors.toSet());
        // 设置点赞数
        Map<Integer, Long> likedCountMap = getLikedCount(commentIds);
        // 判断是否点赞该评论
        Map<Integer, Boolean> LikedMap = getLiked(commentQueryRequest.getUsername(), commentIds);
        // 判断当前用户是否收藏该评论
        Map<Integer, Boolean> collectedMap = getCollected(commentQueryRequest.getUsername(), commentIds);
        // 设置收藏数量
        Map<Integer, Long> collectedCountMap = getCollectedCount(commentIds);

        // 存储 ID 到评论对象的映射
        Map<Integer, CommentDto> commentMap = comments.stream()
                .collect(Collectors.toMap(TbComment::getId, comment ->{
                    CommentDto commentDto = CommentDtoAdaptor.toCommentDto(comment);
                    commentDto.setComment(commentContentMap.get(comment.getComment()));
                    commentDto.setLikedCount(likedCountMap.getOrDefault(comment.getId(), 0L).intValue());
                    commentDto.setLikedFlag(LikedMap.getOrDefault(comment.getId(), Boolean.FALSE));
                    commentDto.setCollectedFlag(collectedMap.getOrDefault(comment.getId(), Boolean.FALSE));
                    commentDto.setCollectedCount(collectedCountMap.getOrDefault(comment.getId(), 0L).intValue());
                    return commentDto;
                }));

        List<TbComment> rootComments = new ArrayList<>();
        for (TbComment comment : comments) {
            if (comment.getReplyId() == 0) {
                // 顶级评论
                rootComments.add(comment);
            } else {
                // 找到父评论，并加入子评论列表
                TbComment parent = commentMap.get(comment.getReplyId());
                if (parent != null) {
                    parent.addReply(comment);
                }
            }
        }
        return rootComments;
    }

    private Map<Integer, String> buildCommentContentMap(List<TbComment> comments) {
        // 获取到所有评论结果
        Set<Integer> setIds = comments.stream()
                .map(TbComment::getComment)
                .collect(Collectors.toSet());
        // 查找出来所有评论
        List<TbEditorData> editorDataList = tbEditorDataService.lambdaQuery()
                .in(TbEditorData::getId, setIds).list();
        // 将 editorDataList 转换为 Map<Integer, String>，其中 key 是 TbEditorData 的 id，value 是 html 字段
        Map<Integer, String> commentIdToHtmlMap = new HashMap<>();
        for (TbEditorData editorData : editorDataList) {
            commentIdToHtmlMap.put(editorData.getId(), editorData.getHtml());
        }
        Map<Integer, String> finalMap = comments.stream()
                .filter(comment -> commentIdToHtmlMap.containsKey(comment.getComment())) // 确保存在对应的 TbEditorData
                .collect(Collectors.toMap(
                        TbComment::getComment, // 使用 TbComment 中的方法来获取 id
                        comment -> commentIdToHtmlMap.get(comment.getComment()) // 获取对应 TbEditorData 的 html
                ));
        return finalMap;
    }
}




